/**
 * 试管架router
 */
import express from "express";
import { Schema } from "mongoose";
import { addData, updateData, findAll, deleteData } from "../mdb/controlDB";
import {
  baseResp,
  shelfModalname,
  shelfSchematype,
  shelfBottleSchematype,
} from "../common";

const router = express.Router();

const bottleSchema = new Schema(shelfBottleSchematype);
const shelfschema = new Schema(shelfSchematype(bottleSchema));

// 新增数据
router.post("/add", function (req, res) {
  const param = req.body;
  const addback = (data: any) => {
    if (data.success === false) {
      res.json(Object.assign({}, baseResp, data));
    } else {
      res.json(Object.assign({}, baseResp));
    }
  };

  addData({
    schematype: shelfschema,
    callback: addback,
    modalname: shelfModalname,
    param,
  });
});

type TBottleInfo = {
  name: string;
  autox: number;
  autoy: number;
  x: number;
  y: number;
  diameter: number;
  rowIndex: number;
  colIndex: number;
  _id?: string;
};

type TShelf = {
  id?: string;
  name: string;
  rackType: string;
  bottleType: string;
  height: number;
  wide: number;
  length: number;
  row: number;
  column: number;
  offsetx: number;
  offsety: number;
  rowSpace: number;
  columnSpace: number;
  bottleList: TBottleInfo[];
  _id?: string;
  __v?: number;
};

// 获取所有试管架
router.get("/all", function (req, res) {
  const param = req.body;

  const findback = (data: any[]) => {
    let temp: TShelf[] = [];
    if (data && data.length) {
      data.forEach((item: TShelf) => {
        const {
          name,
          rackType,
          bottleType,
          height,
          wide,
          length,
          row,
          column,
          offsetx,
          offsety,
          rowSpace,
          columnSpace,
          bottleList,
          _id,
        } = item;

        temp.push({
          id: _id,
          name,
          rackType,
          bottleType,
          height,
          wide,
          length,
          row,
          column,
          offsetx,
          offsety,
          rowSpace,
          columnSpace,
          bottleList,
        });
      });
    }
    res.json(Object.assign({}, baseResp, { data: temp }));
  };

  findAll({
    schematype: shelfschema,
    callback: findback,
    modalname: shelfModalname,
    param,
  });
});

// 删除试管架
router.post("/del", function (req, res) {
  const param = req.body;
  const delback = (data: any) => {
    res.json(Object.assign({}, baseResp, data));
  };

  deleteData({
    schematype: shelfschema,
    callback: delback,
    modalname: shelfModalname,
    param,
  });
});

// 更新试管架
router.post("/update", (req, res) => {
  const param = req.body;
  const updateback = (data: any) => {
    res.json(Object.assign({}, baseResp, { data }));
  };
  updateData({
    schematype: shelfschema,
    callback: updateback,
    modalname: shelfModalname,
    param,
  });
});

export default router;
